import asyncio
Server_IP = "127.0.0.1"
Server_Port = 9966

async def handle_client(
    reader: asyncio.StreamReader, writer: asyncio.StreamWriter
) -> None:
    """处理客户端连接"""
    # 获取客户端地址
    client_addr = writer.get_extra_info("peername")
    print(f"新连接来自 {client_addr}")

    try:
        while True:
            # 读取客户端发送的数据 (最多 1024 字节)
            data = await reader.read(1024)
            if not data:  # 客户端关闭连接
                break

            message = data.decode("utf-8").strip()
            print(f"来自 {client_addr} 的消息: {message}")

            # 回显消息给客户端
            response = f"已收到: {message}\n"
            writer.write(response.encode("utf-8"))
            await writer.drain()  # 确保数据已发送

    except asyncio.CancelledError:
        print(f"客户端 {client_addr} 连接被取消")
    except Exception as e:
        print(f"处理客户端 {client_addr} 时发生错误: {e}")
    finally:
        # 关闭连接
        writer.close()
        await writer.wait_closed()
        print(f"客户端 {client_addr} 连接已关闭")


async def main(host: str = "127.0.0.1", port: int = 9966) -> None:
    """启动异步 TCP 服务端"""
    # 创建异步服务器
    server = await asyncio.start_server(handle_client, host, port)

    # 获取服务器地址
    addr = server.sockets[0].getsockname()
    print(f"服务器运行在 {addr}")

    # 启动服务器并等待其关闭
    async with server:
        await server.serve_forever()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("服务器已关闭")
